package com.nhh.v.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.scala.DefaultScalaModule;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by ywp on 2018/9/3.
 */
@Slf4j
public class JsonUtil {


    private JsonUtil() {
    }

    public static <T> T asJavaObj(String json, Class<T> classType) {

        try {
            return JsonMapperHolder.INSTANCE.getInstance().readValue(json, classType);
        } catch (Exception e) {
            log.error("json deserialize error:" + e.getMessage(), e);
            return null;
        }
    }


    public static String toJsonString(Object json) {
        try {
            return JsonMapperHolder.INSTANCE.getInstance().writeValueAsString(json);
        } catch (JsonProcessingException e) {
            log.error("json serialize error:" + e.getMessage(), e);
            return "";
        }
    }

    private enum JsonMapperHolder {
        INSTANCE;
        private ObjectMapper mapper;

        JsonMapperHolder() {
            mapper = init();
        }

        private ObjectMapper init() {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            mapper.registerModule(new DefaultScalaModule());
            return mapper;
        }

        private ObjectMapper getInstance() {
            return mapper;
        }
    }

}
